package omq.samples;

import java.io.IOException;
import java.rmi.RemoteException;

import javax.xml.rpc.ServiceException;

import omq.api.*;
import omq.api.logger.OmqLogger;

/*
 *  OMQ Sample Codes:
 *  -----------------
 * 
 *  PeekMessage demonstrates how to peek a message in a queue
 *  It uses SOAP to establish connection with the server.
 *  Every message has a messageID and you can access the one of the peeked messages using via sess.getLastMessageID()
 *  
 *  go to
 *  http://www.onlinemq.com/support/index.php/Online_MQ_API#Error_handling
 *  for a list of error codes
 *   
 *  Author  	  	: Hagai Izenberg
 *  Creating Date 	: 02-11-2008
 *  Company 		: OMQI
 */

public class PeekMessage {

	public static void main(String[] args) throws ServiceException, IOException, ClassNotFoundException
	{
		String omqUser = "demo-superadmin";
		String omqPassword = "demokopp";
		String omqQueueManager = "bank";
		String omqQueue = "q1";
		
		OMQConnection con = OMQConnectionFactory.getConnection(omqUser,omqPassword, new OMQQueueManager(omqQueueManager));
		OMQSession sess = con.createSession(false);

		System.out.println("peeking message...");
		OMQMessage msgReceived = sess.peekMessage(new OMQQueue(omqQueue));

		int rc = sess.getLastErrorCode();
		if (rc == 0)
		{
			System.out.println("peeked message successfully");
			System.out.println("peeked message ID = "+sess.getLastMessageID());
			System.out.println("converting message to string object");
			String stringReceived = (String)msgReceived.getMsgBodyAsObject();
			System.out.println("message content="+stringReceived);
		}
		else if (rc == 313) // example for handling specific error code 313 = Queue is empty 
		{
			System.out.println("no message to peek in queue, queue is empty");
		}
		else
		{
			System.err.println("peek message failed");
		}
		System.out.println("LastErrorCode()="+sess.getLastErrorCode()+", LastErrorDescription()="+sess.getLastErrorDescription());
		
		/* check 
		 * http://www.onlinemq.com/support/index.php/Online_MQ_API#Error_handling 
		 * for a list of error codeS
		 */ 
	}

}
